/**
* File Name: sem_pro_consu.c
* Auther: Jichang
* Environment: Fedora 7 server
* about semaphore to realize producer-consumer-model
*/
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<pthread.h>
#include<semaphore.h>

#define NUM 5

int queue[NUM];
sem_t blank_number, product_number;

void *producer(void *arg)
{
	int i = 0;
	while(1) {
		// blank_number--, equals 0 wait.
		sem_wait(&blank_number);
		// produce.
		queue[i] = rand() % 1000 + 1;
		printf("--Produce--%d\n", queue[i]);
		sem_post(&product_number); // product++

		// realize circle
		i = (i+1) % NUM;
		sleep(rand() % 1);
	}
}

void *consumer(void *arg)
{
	int i = 0;
	while(1) {
		// product_number--, equals 0 wait.
		sem_wait(&product_number);
		printf("----Consume--%d\n", queue[i]);
		queue[i] = 0;
		sem_post(&blank_number); //blank_number++

		i = (i+1) % NUM;
		sleep(rand() % 3);
	}
}

int main(int argc, char *argv[])
{
	pthread_t pid, cid;

	// init
	sem_init(&blank_number, 0, NUM); // the rest is 5.
	sem_init(&product_number, 0, 0); // start with 0.

	// create.
	pthread_create(&pid, NULL, producer, NULL);// not check
	pthread_create(&cid, NULL, consumer, NULL);

	// reclaim.
	pthread_join(pid, NULL);
	pthread_join(cid, NULL);

	// destroy.
	sem_destroy(&blank_number);
	sem_destroy(&product_number);

	
	return 0;
}

